package org.stragma.apply.signatures

import org.kiama.rewriting._
import org.kiama.rewriting.Rewriter._

/*
 *	All types defined will inherit from this base type. This type has been
 * introduced to provision features unavailable to Kiama
 */
class TBase {
	
	// This property is used to store attributes of a term
	// Note, the use of an untyped (Any) List, this is
	// because Stratego is untyped and to mimic this we use Any
	var termAttributes = List[Term]()
	
	/*
	 * Adds an attribute to the beginning to the current attribute
	 * list
	 */
	def addAttributeToBeginning(item : Term) = {
		termAttributes ::= item
	}
	
	/*
	 * Adds an attribute to the end of the current attribute list
	 */
	def addAttributeToEnd(item : Term) = {
		termAttributes = termAttributes ::: List(item)
	}
}

object TBase extends TBase {
	/*
	 * This parametrised strategy searches a Terms attributes
	 * and returns the matching attribute
	 */
	def fetch_elem(s : => Strategy) : Strategy = {
		rulefs {
			case attrs : List[Term] =>
				var res2 : Option[Term] = None
				attrs foreach { item =>
					// Apply the strategy to each term, if the strategy does
					// not fail then return that particular result. So in
					// other words return the first item in the list which
					// passes the strategy
					val res = (s <+ fail)(item)
					res match {
						case e : Option[Term] if (e != None)=>
							res2 = e
						case _ => // Do nothing
					}
				}
				res2
		}
	}
}